package com.example.juc.forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 *  如何使用forkjoin
 *  1 forkjoinpoll 来执行
 *  2 计算 forkjoinpoll.excute(ForkJoinTask)
 *  3 计算类要继承ForkJoinTask
 */
public class ForkJoinDemo extends RecursiveTask<Long> {

    private final long start;
    private final long end;
    private final long temp = 10000L;

    public ForkJoinDemo(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        if((end-start)<=temp){
            long sum = 0L;
            for(long i =start ;i<=end;i++){
                sum += i;
            }
            return sum;
        }else {
            long middle = (start + end) /2 ;
            ForkJoinDemo task1 = new ForkJoinDemo(start, middle);
            task1.fork();
            ForkJoinDemo task2 = new ForkJoinDemo(middle+1, end);
            task2.fork();
            return task1.join()+task2.join();
        }
    }

}
